package org.windowkit.toolkit.widget.table.render;

import java.awt.Color;
import java.awt.Component;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;

import org.windowkit.toolkit.widget.table.SortableTableModel;

/**
 * This class renders the "filter row" blue if the table has filtering enabled.
 * @author Eric Lundin
 */
@SuppressWarnings("serial")
public class FilterTableCellRenderer extends DefaultTableCellRenderer {
	private final Color filterBackgroundColor = new Color(200, 200, 255);
	private final Color selectionBackgroundColor = UIManager.getColor("Table.selectionBackground");
	private final Color selectionTextColor = UIManager.getColor("Table.selectionBackground");
	private final Color filterTextColor = UIManager.getColor("Table.foreground");
//	private Color nonFilterBackgroundColor = UIManager.getColor("Table.background");
//	private Color textColor = UIManager.getColor("Table.foreground");

	/**
	 * Constructor.
	 */
	public FilterTableCellRenderer() {
		super();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Component getTableCellRendererComponent(final JTable table,
			final Object value, final boolean isSelected, final boolean hasFocus, final int row,
			final int column) {

		Component component = super.getTableCellRendererComponent(table,
				value, isSelected, hasFocus, row, column);
		boolean filterable = ((SortableTableModel) table.getModel())
				.isFilterable();
		if (row == 0 && filterable) {
			setBackground(filterBackgroundColor);
			setForeground(filterTextColor);
		} else {
			if (isSelected) {
				super.setForeground(table.getSelectionForeground());
				super.setBackground(table.getSelectionBackground());
			} else {
				if (isSelected) {
					super.setForeground(selectionTextColor);
					super.setBackground(selectionBackgroundColor);
				} else {
					super.setForeground(table.getForeground());
					super.setBackground(table.getBackground());
				}
			}
		}
		if (hasFocus) {
			setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
			if (table.isCellEditable(row, column) && !filterable) {
				super.setForeground(UIManager
						.getColor("Table.focusCellForeground"));
				super.setBackground(UIManager
						.getColor("Table.focusCellBackground"));
			}
		} else {
			setBorder(noFocusBorder);
		}

		if (row > ((SortableTableModel) table.getModel()).getDataRowCount()) {
			setBorder(noFocusBorder);
		}
		if (component instanceof JLabel) {
			((JLabel) component).setText(((JLabel) component).getText()
					.replace("\n", " "));

		}
		return component;
	}
}